import { memo, useEffect, useRef } from "react";
import { IndicatorWapper } from "./style";

const Indicator = memo((props) => {
  const { selectIndex = 0 } = props;
  const contentRef = useRef();

  useEffect(() => {
    // 获取对应的元素
    const el = contentRef.current.children[selectIndex];
    // 获取元素左偏移量和本身宽度
    const offsetLeft = el.offsetLeft;
    const clientWidth = el.clientWidth;
    // 获取容器宽度和滚动距离
    const contentWidth = contentRef.current.clientWidth;
    const contentScroll = contentRef.current.scrollWidth;
    const totalDistance = contentScroll - contentWidth;
    // 计算滚动距离
    let distance = offsetLeft + clientWidth * 0.5 - contentWidth * 0.5;

    if (distance < 0) distance = 0;
    if (distance > totalDistance) distance = totalDistance;

    contentRef.current.style.transform = `translate(${-distance}px)`;
  }, [selectIndex]);

  return (
    <IndicatorWapper>
      <div className="i-content" ref={contentRef}>
        {props.children}
      </div>
    </IndicatorWapper>
  );
});

export default Indicator;
